package br.ufpe.cin.dsoa.qos.monitoring;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import br.ufpe.cin.dsoa.qos.monitoring.service.events.QoSAttribute;

public class LogQoSAttribute {
	private static final String driver = "org.apache.derby.jdbc.ClientDriver";
	private static final String url = "jdbc:derby://localhost:1527/Database/QosDB;traceFile=trace.log";
	private static Properties config;
	
	static {
		try {
			Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		config = new Properties();
		config.setProperty("proxool.maximum-connection-count", "100");
	}
	
	private static Connection getConnection() throws SQLException {
		return DriverManager.getConnection("proxool.agencia:" + driver + ":" + url,config);
	}
	
	public static void log(QoSAttribute qos) {
		Connection conn = null;
		PreparedStatement psInsert = null;
		System.out.println(qos);
		try {
			conn = getConnection();

			psInsert = conn
			.prepareStatement("INSERT INTO QOS_ATTRIBUTE(QOS_ATTRIBUTE, QOS_SERVICE, QOS_OPERATION, QOS_CONSUMER, QOS_VALUE) VALUES (?, ?, ?, ?, ?)");

			psInsert.setString(1, qos.getClass().getSimpleName());
			psInsert.setString(2, qos.getServiceId());
			psInsert.setString(3, qos.getOperationName());
			psInsert.setString(4, qos.getConsumerId());
			psInsert.setDouble(5, qos.getValue());
			
			psInsert.executeUpdate();

		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			if (psInsert != null) {
				try {
					psInsert.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

		}
	}
	
}
